package com.yhao.stocknew.common.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;

/**
 * @author : yhao
 * @Date : 2022/4/20 - 21:47
 * @Desc : TODO
 */
public class HttpClientUtils {

    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 设置连接主机超时时间，单位毫秒。
     */
    private static final Integer CONNECT_TIMEOUT = 30000;

    /**
     * 设置连接请求超时时间，单位毫秒。
     */
    private static final Integer CONNECTION_REQUEST_TIMEOUT = 30000;

    /**
     * 请求获取数据的超时时间(即响应时间)，单位毫秒。
     */
    private static final Integer SOCKET_TIMEOUT = 30000;

    /**
     * 发送get请求
     *
     * @param url 链接
     * @return 执行结果
     */
    public static String doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 发送get请求
     *
     * @param url    链接
     * @param params 请求参数
     * @return 执行结果
     */
    public static String doGet(String url, Map<String, String> params) {
        return doGet(url, null, params);
    }

    /**
     * 发送get请求
     *
     * @param url     链接
     * @param headers 请求头
     * @param params  请求参数
     * @return 执行结果
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) {
        // 创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建response对象
        CloseableHttpResponse response = null;
        // 响应结果
        String result = null;
        try {
            // 创建访问地址，处理请求参数
            URIBuilder uriBuilder = handleParam(url, params);
            // 创建http对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 处理config参数
            handleConfig(httpGet);
            // 处理请求头
            handleHeader(headers, httpGet);
            // 执行请求
            response = client.execute(httpGet);
            // 响应结果
            result = EntityUtils.toString(response.getEntity(), ENCODING);
        } catch (Exception e) {
            e.getMessage();
        } finally {
            // 释放资源
            release(client, response);
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url     链接
     * @param headers 请求头
     * @return 执行结果
     */
    public static String doPost(String url, Map<String, String> headers) {
        return doPost(url, headers, null, null);
    }

    /**
     * 发送post请求
     *
     * @param url     链接
     * @param headers 请求头
     * @param params  请求参数
     * @return 执行结果
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, String> params) {
        return doPost(url, headers, params, null);
    }

    /**
     * 发送post请求
     *
     * @param url     链接
     * @param headers 请求头
     * @param body    请求体
     * @return 执行结果
     */
    public static String doPost(String url, Map<String, String> headers, String body) {
        return doPost(url, headers, null, body);
    }

    /**
     * 发送post请求
     *
     * @param url     链接
     * @param headers 请求头
     * @param params  请求参数
     * @param body    请求体
     * @return 执行结果
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, String> params, String body) {
        // 创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建response对象
        CloseableHttpResponse response = null;
        // 响应结果
        String result = null;
        try {
            // 创建访问地址，处理请求参数
            URIBuilder uriBuilder = handleParam(url, params);
            // 创建http对象
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            // 处理config参数
            handleConfig(httpPost);
            // 处理请求头
            handleHeader(headers, httpPost);
            // 处理请求体
            handleBody(body, httpPost);
            // 执行请求
            response = client.execute(httpPost);
            // 响应结果
            result = EntityUtils.toString(response.getEntity(), ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(client, response);
        }
        return result;
    }

    /**
     * 发送delete请求
     *
     * @param url 链接
     * @return 执行结果
     */
    public static String doDelete(String url) throws IOException {
        return doDelete(url, null, null);
    }

    /**
     * 发送delete请求
     *
     * @param url     链接
     * @param headers 请求头
     * @param params  请求参数
     * @return 执行结果
     */
    public static String doDelete(String url, Map<String, String> headers, Map<String, String> params) {
        // 创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建response对象
        CloseableHttpResponse response = null;
        // 响应结果
        String result = null;
        try {
            // 创建访问地址，处理请求参数
            URIBuilder uriBuilder = handleParam(url, params);
            // 创建http对象
            HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
            // 处理config参数
            handleConfig(httpDelete);
            // 处理请求头
            handleHeader(headers, httpDelete);
            // 执行请求
            response = client.execute(httpDelete);
            // 响应对象
            result = EntityUtils.toString(response.getEntity(), ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(client, response);
        }
        return result;
    }

    /**
     * 处理请求参数
     *
     * @param url    链接
     * @param params 请求参数
     * @return 执行结果
     */
    private static URIBuilder handleParam(String url, Map<String, String> params) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        return uriBuilder;
    }

    /**
     * 处理config设置
     *
     * @param httpMethod 方法对象
     */
    private static void handleConfig(HttpRequestBase httpMethod) {
        if (httpMethod != null) {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .build();
            httpMethod.setConfig(requestConfig);
        }
    }

    /**
     * 处理请求头
     *
     * @param params     请求参数
     * @param httpMethod 方法对象
     */
    private static void handleHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 处理请求体
     *
     * @param body     请求体
     * @param httpPost 方法对象
     */
    private static void handleBody(String body, HttpPost httpPost) {
        if (body != null) {
            httpPost.setEntity(new StringEntity(body, ENCODING));
        }
    }

    /**
     * 释放资源
     *
     * @param client   客户端连接对象
     * @param response 响应对象
     */
    private static void release(CloseableHttpClient client, CloseableHttpResponse response) {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
